package com.zxw.设计模式.结构型.装饰器模式.装饰者;

import com.zxw.设计模式.结构型.装饰器模式.抽象构建角色.DataLoader;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

/**
 * @projectName: util-cloud
 * @package: com.zxw.设计模式.结构型.装饰器模式.装饰者
 * @className: EncryptionDataDecorator
 * @author: zhangxuewei
 * @description: 具体装饰着-对文件加密、解密
 * @date: 2023/7/1 17:34
 * @version: 1.0
 */
public class EncryptionDataDecorator extends DataLoderDecorator {

    public EncryptionDataDecorator(DataLoader dataLoader) {
        super(dataLoader);
    }

    @Override
    public String read() {
        return decode(super.read());
    }

    @Override
    public void write(String data) {
        super.write(encode(data));
    }

    /**
     * @param data:
     * @return String
     * @author zhangxuewei
     * @description 加密
     * @date 2023/7/1 17:41
     */
    public String encode(String data) {
        try {
            Base64.Encoder encoder = Base64.getEncoder();
            byte[] bytes = data.getBytes("UTF-8");
            String res = encoder.encodeToString(bytes);
            return res;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public String decode(String data) {
        try {
            Base64.Decoder decode = Base64.getDecoder();
            String res = new String(decode.decode(data), "UTF-8");
            return res;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }



}
